package leetcode_周赛._2023._12;

import java.util.Arrays;

/**
 * 第 376 场周赛
 * AC_2
 *
 * @author yezh
 * @date 2023/12/18 8:55
 */
public class _17 {

    /**
     * 2967. 使数组成为等数数组的最小代价
     * 算法：
     */
    public long minimumCost(int[] nums) {
        Arrays.sort(nums);
        int n = nums.length;
        int i = lowerBound(nums[(n - 1) / 2]);
        if (pal[i] <= nums[n / 2]) return cost(nums, pal[i]);
        return Math.min(cost(nums, pal[i - 1]), cost(nums, pal[i]));
    }

    long cost(int[] nums, int t) {
        long ans = 0;
        for (int num : nums) ans += Math.abs(num - t);
        return ans;
    }

    int lowerBound(int target) {
        int l = 0, r = pal.length - 1;
        while (l <= r) {
            int mid = l + (r - l) / 2;
            if (pal[mid] < target) l = mid + 1;
            else r = mid - 1;
        }
        return l;
    }

    static int[] pal = new int[109999];

    static {
        int idx = 0;
        for (int base = 1; base <= 10000; base *= 10) {
            // 生成奇数长度回文数
            for (int i = base; i < base * 10; i++) {
                int x = i;
                for (int t = i / 10; t > 0; t /= 10) x = x * 10 + t % 10;
                pal[idx++] = x;
            }
            // 生成偶数长度回文数
            if (base <= 1000) {
                for (int i = base; i < base * 10; i++) {
                    int x = i;
                    for (int t = i; t > 0; t /= 10) x = x * 10 + t % 10;
                    pal[idx++] = x;
                }
            }
        }
        // 哨兵，防止下面代码中的 i 下标越界
        pal[idx] = 1_000_000_001;
    }

}
